/**
 * Created by wzl on 2017/4/19.
 */
import axios from "axios"

export function search(){
    return function(dispatch){
        dispatch({type:"FETCH_SEARCH_RESULT"});
        axios.get('http://map.tianditu.com/query.shtml?postStr={"keyWord":"天安门","level":"12","mapBound":"-180,-90,180,90","queryType":"1","start":"0","count":"10"}&type=query')
            .then((response)=>{
                dispatch({type:"RECEIVE_SEARCH_RESULT",payload:response.data})
            })
            .catch((err)=>{
                dispatch({type:"FETCH_RESULT_ERROR",payload:err})
            })
    }
}

export function loadTiles(x,y,level){
    let url=`https://b.tiles.mapbox.com/v4/mapbox.mapbox-terrain-v2,mapbox.mapbox-streets-v7/${level}/${x}/${y}.vector.pbf?access_token=pk.eyJ1Ijoid3psaDAwNyIsImEiOiJjaW5mdm83cTIxNnNvdmdrdjU0YXMxNjZ4In0.yQNP1GTVJkTHI7fQsSCLJw`;
    // console.log(url);
    return function(dispatch){
        dispatch({type:"FETCH_SEARCH_RESULT"});
        axios({
            method:'get',
            url:url,
            responseType:'arraybuffer'
        })
            .then((response)=>{
            // console.log('get response: ',response.data)
                dispatch({type:"RECEIVE_SEARCH_RESULT",payload:response.data})
            })
            .catch((err)=>{
                dispatch({type:"FETCH_RESULT_ERROR",payload:err})
            })
    }
}

export function loadMultipleTiles(arr){
    // console.log('arr',arr);
    return function(dispatch){
        let promises = arr.map((tile)=>{
            let level = tile.level;
            let x = tile.x;
            let y = tile.y;
            let url = `https://b.tiles.mapbox.com/v4/mapbox.mapbox-terrain-v2,mapbox.mapbox-streets-v7/${level}/${x}/${y}.vector.pbf?access_token=pk.eyJ1Ijoid3psaDAwNyIsImEiOiJjaW5mdm83cTIxNnNvdmdrdjU0YXMxNjZ4In0.yQNP1GTVJkTHI7fQsSCLJw`;
            return axios({
                method:'get',
                url:url,
                responseType:'arraybuffer'
            });
        });
        dispatch({type:"FETCH_SEARCH_RESULT"});
        // console.log('promises',promises);
        axios.all(promises).then(function(results) {
            // console.log(results);
            let data = results.map(function(response) {
                return response.data;
            })
            dispatch({type:"RECEIVE_SEARCH_RESULT",payload:data})
        })
            .catch((err)=>{
                dispatch({type:"FETCH_RESULT_ERROR",payload:err})
            })
    }

}